import { defineStore } from 'pinia';
import { 
  getLands, addLand, updateLand, deleteLand,
  getPlantings, addPlanting, updatePlanting, deletePlanting, recordHarvest,
  getFertilizingRecords, addFertilizingRecord, updateFertilizingRecord, deleteFertilizingRecord,
  getInventory, getInventoryByType, getLowInventory,
  getOrders, getTransactions, getTransactionStats, createTransaction, createOrder, payOrder,
  getCropTypes, getFertilizers,
  addInventory,
  updateInventory,
  deleteInventory,
  getMyProducts,
  getMySellOrders,
  addProduct,
  updateProduct,
  deleteProduct,
  uploadProductImage,
  publishProduct,
  unpublishProduct,
  shipOrder,
  getAllMyOrders,
  getMyBuyOrders,
  receiveOrder
} from '../../api/farmer';

export const useFarmerStore = defineStore('farmer', {
  state: () => ({
    lands: [],
    plantings: [],
    fertilizingRecords: [],
    inventory: [],
    lowInventoryItems: [],
    orders: [],
    transactions: [],
    currentLand: null,
    currentPlanting: null,
    fertilizingStatus: {}, // 存储施肥状态，如：{ plantingId: 'green'|'yellow'|'red' }
    // 本地存储的收获日期映射表 (ID -> harvestDate)
    harvestDatesMap: {},
    cropTypes: [],
    fertilizers: []
  }),

  getters: {
    landById: (state) => (id) => state.lands.find(land => land.id === id),
    plantingById: (state) => (id) => state.plantings.find(planting => planting.id === id),
    plantingsByLandId: (state) => (landId) => state.plantings.filter(planting => planting.landId === landId),
    fertilizingRecordsByPlantingId: (state) => (plantingId) => 
      state.fertilizingRecords.filter(record => record.plantingId === plantingId),
    overdueWarnings: (state) => 
      Object.entries(state.fertilizingStatus).filter(([_, status]) => status === 'red').length,
    upcomingWarnings: (state) => 
      Object.entries(state.fertilizingStatus).filter(([_, status]) => status === 'yellow').length,
    totalInventoryValue: (state) => 
      state.productInventory.reduce((sum, item) => sum + item.quantity * item.price, 0)
  },

  actions: {
    // 土地管理
    async fetchLands() {
      try {
        const response = await getLands();
        console.log('获取土地列表响应:', response);
        
        // 处理后端返回的数据结构
        let lands = [];
        
        if (response) {
          // 如果是直接返回数组
          if (Array.isArray(response)) {
            lands = response;
          } 
          // 如果是嵌套在data中
          else if (response.data) {
            // 如果返回的是分页对象，提取 records 数组
            if (response.data.records) {
              lands = response.data.records;
            } else if (Array.isArray(response.data)) {
              lands = response.data;
            } else {
              lands = [response.data]; // 单个对象转为数组
            }
          }
        }
        
        console.log('处理后的土地列表:', lands);
        this.lands = lands;
        return Promise.resolve(lands);
      } catch (error) {
        console.error('获取土地列表失败', error);
        return Promise.reject(error);
      }
    },

    async createLand(landData) {
      console.log('Store: 开始创建土地', landData);
      try {
        const newLand = await addLand(landData);
        console.log('Store: 土地创建成功', newLand);
        // 确保lands数组已初始化
        if (!this.lands) {
          this.lands = [];
        }
        this.lands.push(newLand);
        return Promise.resolve(newLand);
      } catch (error) {
        console.error('Store: 创建土地失败', error);
        return Promise.reject(error);
      }
    },

    async updateLandInfo(id, landData) {
      try {
        const updatedLand = await updateLand(id, landData);
        const index = this.lands.findIndex(land => land.id === id);
        if (index !== -1) {
          this.lands[index] = updatedLand;
        }
        return Promise.resolve(updatedLand);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    async removeLand(id) {
      try {
        await deleteLand(id);
        this.lands = this.lands.filter(land => land.id !== id);
        return Promise.resolve();
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 种植管理
    async fetchPlantings() {
      try {
        const response = await getPlantings();
        console.log('获取种植记录响应:', response);
        
        // 处理后端返回的数据结构
        let plantings = [];
        
        if (response) {
          // 如果是直接返回数组
          if (Array.isArray(response)) {
            plantings = response;
          } 
          // 如果是嵌套在data中
          else if (response.data) {
            // 如果返回的是分页对象，提取 records 数组
            if (response.data.records) {
              plantings = response.data.records;
            } else if (Array.isArray(response.data)) {
              plantings = response.data;
            } else {
              plantings = [response.data]; // 单个对象转为数组
            }
          }
        }
        
        // 处理每条记录，确保包含所有必要字段
        plantings = plantings.map(planting => {
          // 找到对应的土地信息
          const land = this.lands.find(l => l.id === planting.landId);
          
          // 确保记录包含landName字段
          if (land && !planting.landName) {
            planting.landName = land.name;
          }
          
          return planting;
        });
        
        console.log('处理后的种植记录:', plantings);
        this.plantings = plantings;
        return plantings;
      } catch (error) {
        console.error('获取种植记录失败', error);
        throw error;
      }
    },

    async addNewPlanting(plantingData) {
      try {
        console.log('添加种植记录，提交数据:', plantingData);
        const response = await addPlanting(plantingData);
        console.log('添加种植记录响应:', response);
        
        // 处理后端返回的数据
        let newPlanting = plantingData; // 默认使用提交的数据
        
        if (response) {
          if (response.data) {
            // 如果返回的是分页对象，提取 records 数组中的第一条
            if (response.data.records && response.data.records.length > 0) {
              newPlanting = response.data.records[0];
            } else {
              newPlanting = response.data;
            }
          } else {
            newPlanting = response;
          }
        }
        
        // 确保添加到本地数据中的记录有id
        if (newPlanting && newPlanting.id) {
          // 保存预计收获日期到本地映射表
          if (plantingData.harvestDate) {
            this.harvestDatesMap[newPlanting.id] = plantingData.harvestDate;
          }
          
          // 确保harvestDate字段存在
          if (plantingData.harvestDate && !newPlanting.harvestDate) {
            newPlanting.harvestDate = plantingData.harvestDate;
          }
          
          // 确保expectedYield字段存在
          if (plantingData.expectedYield && !newPlanting.expectedYield) {
            newPlanting.expectedYield = plantingData.expectedYield;
          }
          
          // 获取土地名称
          const land = this.lands.find(l => l.id === newPlanting.landId);
          if (land && !newPlanting.landName) {
            newPlanting.landName = land.name;
          }
          
          // 合并原始提交的数据，确保所有字段都存在
          newPlanting = {
            ...plantingData,
            ...newPlanting
          };
          
          this.plantings.push(newPlanting);
        } else {
          // 如果没有返回完整记录，重新获取所有记录
          await this.fetchPlantings();
        }
        
        return newPlanting;
      } catch (error) {
        console.error('添加种植记录失败', error);
        throw error;
      }
    },

    async updatePlanting(id, plantingData) {
      try {
        console.log('更新种植记录，ID:', id, '提交数据:', plantingData);
        
        // 保存预计收获日期到本地映射表
        if (plantingData.harvestDate) {
          this.harvestDatesMap[id] = plantingData.harvestDate;
        }
        
        // 调用API更新种植记录
        const response = await updatePlanting(id, plantingData);
        console.log('更新种植记录响应:', response);
        
        // 更新本地数据
        const index = this.plantings.findIndex(planting => planting.id === id);
        
        if (index === -1) {
          // 如果本地没有这条记录，重新获取所有记录
          console.log('本地没有找到记录，重新获取所有种植记录');
          await this.fetchPlantings();
          return response;
        }
        
        let updatedPlanting = { ...this.plantings[index] }; // 保留原始记录的所有字段
        
        // 根据API响应类型不同进行不同处理
        if (response && typeof response === 'object' && response.data) {
          // 如果API返回了完整的数据对象
          const responseData = { ...response.data };
          
          // 合并数据，保留原始对象的字段
          updatedPlanting = {
            ...updatedPlanting,
            ...responseData
          };
        } else {
          // 如果API返回的是简单类型（如布尔值）或没有返回data字段
          console.log('API返回值不包含完整数据，使用本地提交的数据更新');
          updatedPlanting = { 
            ...updatedPlanting, 
            ...plantingData,
            // 确保更新日期字段
            updateTime: new Date().toISOString()
          };
        }
        
        // 确保重要字段存在
        if (plantingData.harvestDate && !updatedPlanting.harvestDate) {
          updatedPlanting.harvestDate = plantingData.harvestDate;
        }
        
        if (plantingData.expectedYield && !updatedPlanting.expectedYield) {
          updatedPlanting.expectedYield = plantingData.expectedYield;
        }
        
        // 获取土地名称
        if (plantingData.landId && !updatedPlanting.landName) {
          const land = this.lands.find(l => l.id === plantingData.landId);
          if (land) {
            updatedPlanting.landName = land.name;
          }
        }
        
        // 更新本地数据
        this.plantings[index] = updatedPlanting;
        
        return response;
      } catch (error) {
        console.error('更新种植记录失败', error);
        throw error;
      }
    },
    
    async removePlanting(id) {
      try {
        await deletePlanting(id);
        this.plantings = this.plantings.filter(planting => planting.id !== id);
        return Promise.resolve();
      } catch (error) {
        console.error('删除种植记录失败', error);
        return Promise.reject(error);
      }
    },

    // 施肥管理
    async fetchFertilizingRecords() {
      try {
        const response = await getFertilizingRecords();
        // 处理后端返回的格式，确保数据正确赋值到store中
        if (response.success && response.data) {
          this.fertilizingRecords = response.data || [];
          return this.fertilizingRecords;
        } else {
          console.error('获取施肥记录失败', response.message);
          return [];
        }
      } catch (error) {
        console.error('获取施肥记录失败', error);
        return [];
      }
    },

    async addFertilizingRecord(data) {
      try {
        // 处理日期格式
        const formattedData = {
          ...data
        };
        
        if (formattedData.date && formattedData.date instanceof Date) {
          // 使用本地时区格式化日期，避免时区问题
          const year = formattedData.date.getFullYear();
          const month = String(formattedData.date.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.date.getDate()).padStart(2, '0');
          formattedData.date = `${year}-${month}-${day}T00:00:00`;
        }

        const response = await addFertilizingRecord(formattedData);
        if (response.success) {
          await this.fetchFertilizingRecords(); // 重新获取列表
          return response.data;
        } else {
          throw new Error(response.message || '添加施肥记录失败');
        }
      } catch (error) {
        console.error('添加施肥记录失败', error);
        throw error;
      }
    },

    async updateFertilizingRecord(id, data) {
      try {
        // 处理日期格式
        const formattedData = {
          ...data
        };
        
        if (formattedData.date && formattedData.date instanceof Date) {
          // 使用本地时区格式化日期，避免时区问题
          const year = formattedData.date.getFullYear();
          const month = String(formattedData.date.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.date.getDate()).padStart(2, '0');
          formattedData.date = `${year}-${month}-${day}T00:00:00`;
        }

        const response = await updateFertilizingRecord(id, formattedData);
        if (response.success) {
          await this.fetchFertilizingRecords(); // 重新获取列表
          return response.data;
        } else {
          throw new Error(response.message || '更新施肥记录失败');
        }
      } catch (error) {
        console.error('更新施肥记录失败', error);
        throw error;
      }
    },

    async deleteFertilizingRecord(id) {
      try {
        const response = await deleteFertilizingRecord(id);
        if (response.success) {
          await this.fetchFertilizingRecords(); // 重新获取列表
          return response.data;
        } else {
          throw new Error(response.message || '删除施肥记录失败');
        }
      } catch (error) {
        console.error('删除施肥记录失败', error);
        throw error;
      }
    },

    calculateFertilizingStatus() {
      // 计算每个种植的施肥状态
      const status = {};
      
      this.plantings.forEach(planting => {
        if (!planting.active) return;
        
        const records = this.fertilizingRecords
          .filter(record => record.plantingId === planting.id)
          .sort((a, b) => new Date(b.date) - new Date(a.date));
        
        if (records.length === 0) {
          status[planting.id] = 'green'; // 新种植默认为绿色
          return;
        }
        
        const lastRecord = records[0];
        const nextDate = new Date(lastRecord.nextFertilizingDate);
        const today = new Date();
        const diffDays = Math.floor((nextDate - today) / (1000 * 60 * 60 * 24));
        
        if (diffDays < 0) {
          status[planting.id] = 'red'; // 超期
        } else if (diffDays <= 2) {
          status[planting.id] = 'yellow'; // 即将到期
        } else {
          status[planting.id] = 'green'; // 正常
        }
      });
      
      this.fertilizingStatus = status;
    },

    // 库存管理
    async fetchInventory() {
      try {
        const response = await getInventory();
        this.inventory = response.data || [];
        return this.inventory;
      } catch (error) {
        console.error('获取库存失败', error);
        return [];
      }
    },

    // 获取某类型库存
    async fetchInventoryByType(type) {
      try {
        const response = await getInventoryByType(type);
        return response.data || [];
      } catch (error) {
        console.error(`获取${type}库存失败`, error);
        return [];
      }
    },

    // 获取低库存预警
    async fetchLowInventory() {
      try {
        const response = await getLowInventory();
        this.lowInventoryItems = response.data || [];
        return this.lowInventoryItems;
      } catch (error) {
        console.error('获取低库存预警失败', error);
        return [];
      }
    },

    // 添加库存
    async addInventory(data) {
      try {
        // 处理日期格式
        const formattedData = {
          ...data
        };
        
        if (formattedData.date && formattedData.date instanceof Date) {
          // 使用本地时区格式化日期，避免时区问题
          const year = formattedData.date.getFullYear();
          const month = String(formattedData.date.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.date.getDate()).padStart(2, '0');
          formattedData.date = `${year}-${month}-${day}T00:00:00`;
        }
        
        // 同样处理生产日期和过期日期
        if (formattedData.productionDate && formattedData.productionDate instanceof Date) {
          const year = formattedData.productionDate.getFullYear();
          const month = String(formattedData.productionDate.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.productionDate.getDate()).padStart(2, '0');
          formattedData.productionDate = `${year}-${month}-${day}T00:00:00`;
        }
        
        if (formattedData.expiryDate && formattedData.expiryDate instanceof Date) {
          const year = formattedData.expiryDate.getFullYear();
          const month = String(formattedData.expiryDate.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.expiryDate.getDate()).padStart(2, '0');
          formattedData.expiryDate = `${year}-${month}-${day}T00:00:00`;
        }

        const response = await addInventory(formattedData);
        await this.fetchInventory();
        return response.data;
      } catch (error) {
        console.error('添加库存失败', error);
        throw error;
      }
    },

    // 更新库存
    async updateInventory(id, data) {
      try {
        console.log('更新库存开始，ID:', id, '数据:', data);
        
        // 处理日期格式
        const formattedData = {
          ...data,
          // 确保包含id字段而不是itemId
          id: id
        };
        
        // 删除itemId字段，如果存在的话
        if (formattedData.itemId) {
          delete formattedData.itemId;
        }
        
        if (formattedData.date && formattedData.date instanceof Date) {
          // 使用本地时区格式化日期，避免时区问题
          const year = formattedData.date.getFullYear();
          const month = String(formattedData.date.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.date.getDate()).padStart(2, '0');
          formattedData.date = `${year}-${month}-${day}T00:00:00`;
        }
        
        // 同样处理生产日期和过期日期
        if (formattedData.productionDate && formattedData.productionDate instanceof Date) {
          const year = formattedData.productionDate.getFullYear();
          const month = String(formattedData.productionDate.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.productionDate.getDate()).padStart(2, '0');
          formattedData.productionDate = `${year}-${month}-${day}T00:00:00`;
        }
        
        if (formattedData.expiryDate && formattedData.expiryDate instanceof Date) {
          const year = formattedData.expiryDate.getFullYear();
          const month = String(formattedData.expiryDate.getMonth() + 1).padStart(2, '0');
          const day = String(formattedData.expiryDate.getDate()).padStart(2, '0');
          formattedData.expiryDate = `${year}-${month}-${day}T00:00:00`;
        }

        console.log('格式化后的更新数据:', formattedData);
        const response = await updateInventory(id, formattedData);
        console.log('更新库存响应:', response);
        
        // 检查响应，如果更新失败则提供更清晰的错误
        if (response.data === false) {
          console.error('更新库存返回false，可能是ID不匹配');
          throw new Error('更新库存失败，请检查记录ID是否正确');
        }
        
        await this.fetchInventory();
        return response.data;
      } catch (error) {
        console.error('更新库存失败', error);
        throw error;
      }
    },

    // 删除库存
    async deleteInventory(id) {
      try {
        const response = await deleteInventory(id);
        await this.fetchInventory();
        return response.data;
      } catch (error) {
        console.error('删除库存失败', error);
        throw error;
      }
    },

    // 获取农产品列表
    async fetchProducts() {
      try {
        const response = await getMyProducts();
        console.log('获取农产品列表:', response);
        
        if (!response || !response.data) {
          return [];
        }
        
        // 处理获取到的产品数据
        const products = response.data.map(product => {
          return {
            id: product.id,
            name: product.name,
            category: product.type,
            price: product.price,
            unit: product.unit,
            stock: product.stock,
            image: product.image,
            status: Number(product.status), // 保持数字状态值，确保是数字类型
            description: product.description,
            createdAt: product.createTime,
            productionDate: product.productionDate
          };
        });
        
        return products;
      } catch (error) {
        console.error('获取农产品列表失败', error);
        return [];
      }
    },

    // 添加农产品
    async addProduct(productData) {
      try {
        console.log('添加产品', productData);
        const response = await addProduct(productData);
        return response;
      } catch (error) {
        console.error('添加产品失败', error);
        throw error;
      }
    },

    // 更新农产品
    async updateProduct(productData) {
      try {
        console.log('更新产品:', productData);
        const response = await updateProduct(productData);
        return response;
      } catch (error) {
        console.error('更新产品失败', error);
        throw error;
      }
    },

    // 删除农产品
    async deleteProduct(id) {
      try {
        console.log('删除产品', id);
        const response = await deleteProduct(id);
        return response;
      } catch (error) {
        console.error('删除产品失败', error);
        throw error;
      }
    },

    // 获取农户订单
    async fetchOrders() {
      try {
        const response = await getAllMyOrders();
        console.log('获取农户所有订单:', response);
        
        if (!response || !response.data) {
          return [];
        }
        
        // 处理获取到的订单数据
        const orders = response.data.map(order => {
          // 订单状态转换
          let status = 'pending';
          switch (order.status) {
            case 0: status = 'pending'; break;  // 待付款
            case 1: status = 'paid'; break;     // 待发货
            case 2: status = 'shipped'; break;  // 待收货
            case 3: status = 'completed'; break; // 已完成
            case 4: status = 'cancelled'; break; // 已取消
            default: status = 'pending';
          }
          
          // 判断订单类型
          const isFertilizerOrder = order.orderType === 1; // 1表示肥料订单
          
          return {
            id: order.id,
            orderNo: order.orderNo,
            buyerId: order.buyerId,
            buyerName: order.buyerName,
            sellerId: order.sellerId,
            sellerName: order.sellerName,
            productId: order.productId,
            productName: order.productName,
            productImage: order.productImage,
            price: order.price,
            quantity: order.quantity,
            totalAmount: order.totalAmount,
            status,
            orderType: order.orderType, // 添加订单类型
            isFertilizerOrder, // 添加是否为肥料订单的标志
            contactName: order.contactName,
            contactPhone: order.contactPhone,
            address: order.address,
            orderTime: order.orderTime,
            payTime: order.payTime,
            shipTime: order.shipTime,
            completeTime: order.completeTime,
            remark: order.remark,
            createTime: order.createTime,
            updateTime: order.updateTime
          };
        });
        
        return orders;
      } catch (error) {
        console.error('获取订单失败', error);
        return [];
      }
    },

    // 订单发货
    async shipOrder(orderId, shipData) {
      try {
        const response = await shipOrder(orderId, shipData);
        return {
          success: true,
          ...response
        };
      } catch (error) {
        console.error('发货失败', error);
        return { success: false, message: error.message || '发货失败' };
      }
    },

    /**
     * 确认收货
     */
    async receiveOrder(orderId) {
      try {
        const response = await receiveOrder(orderId);
        return {
          success: true,
          ...response
        };
      } catch (error) {
        console.error('确认收货失败', error);
        return { success: false, message: error.message || '确认收货失败' };
      }
    },

    // 取消订单
    async cancelOrder(orderId) {
      try {
        // TODO: 实现API调用
        // Mock响应
        return {
          success: true,
          message: '订单取消成功',
          data: {
            orderId,
            status: 'cancelled',
            cancelDate: new Date().toISOString()
          }
        };
      } catch (error) {
        console.error('取消订单失败', error);
        throw error;
      }
    },

    // 获取交易记录
    async fetchTransactions(params) {
      try {
        console.log('获取交易记录，参数:', params);
        const response = await getTransactions(params);
        console.log('获取交易记录响应:', response);
        
        if (response && response.success) {
          // 格式化数据，确保前端需要的字段都存在
          const transactions = response.data.map(transaction => {
            return {
              id: transaction.id,
              type: transaction.type,
              orderNumber: transaction.orderNumber,
              productName: transaction.productName,
              quantity: transaction.quantity,
              unit: transaction.unit || '个',
              amount: transaction.amount,
              transactionDate: transaction.transactionDate,
              note: transaction.note
            };
          });
          return transactions;
        } else {
          console.error('获取交易记录失败:', response && response.message ? response.message : '未知错误');
          return [];
        }
      } catch (error) {
        console.error('获取交易记录失败', error);
        return [];
      }
    },
    
    // 获取交易统计
    async getTransactionStats() {
      try {
        console.log('开始获取交易统计数据');
        const response = await getTransactionStats();
        console.log('获取交易统计响应:', response);
        
        if (response && response.success) {
          // 确保数据格式正确
          let statsData = response.data || {};
          
          // 确保所有必要字段都存在
          return {
            incomeTotal: statsData.incomeTotal || 0,
            expenseTotal: statsData.expenseTotal || 0,
            balance: statsData.netIncome || 0  // 注意这里使用的是netIncome字段
          };
        } else {
          const errorMsg = response && response.message ? response.message : '未知错误';
          console.error('获取交易统计失败:', errorMsg);
          // 返回默认值
          return this.getDefaultTransactionStats();
        }
      } catch (error) {
        console.error('获取交易统计失败', error);
        // 返回默认值
        return this.getDefaultTransactionStats();
      }
    },

    // 获取默认的交易统计数据
    getDefaultTransactionStats() {
      return {
        incomeTotal: 0,
        expenseTotal: 0,
        balance: 0
      };
    },

    // 创建交易记录
    async createTransaction(transactionData) {
      try {
        console.log('创建交易记录，数据:', transactionData);
        const response = await createTransaction(transactionData);
        console.log('创建交易记录响应:', response);
        
        if (response && response.success) {
          return response.data;
        } else {
          console.error('创建交易记录失败:', response && response.message ? response.message : '未知错误');
          return null;
        }
      } catch (error) {
        console.error('创建交易记录失败', error);
        return null;
      }
    },

    // 创建订单
    async createOrder(orderData) {
      try {
        console.log('创建订单，数据:', orderData);
        const response = await createOrder(orderData);
        console.log('创建订单响应:', response);
        
        if (response && response.success) {
          return response.data;
        } else {
          console.error('创建订单失败:', response && response.message ? response.message : '未知错误');
          return null;
        }
      } catch (error) {
        console.error('创建订单失败', error);
        return null;
      }
    },

    // 获取农作物信息
    async fetchCropTypes() {
      try {
        const response = await getCropTypes();
        this.cropTypes = response.data || [];
        return this.cropTypes;
      } catch (error) {
        console.error('获取作物类型失败', error);
        // 返回空数组，不提供默认值
        this.cropTypes = [];
        return [];
      }
    },
    
    // 获取肥料信息
    async fetchFertilizers() {
      try {
        const response = await getFertilizers();
        this.fertilizers = response.data || [];
        return this.fertilizers;
      } catch (error) {
        console.error('获取肥料列表失败', error);
        return [];
      }
    },

    // 记录收获
    async recordPlantingHarvest(id, actualYield) {
      try {
        const response = await recordHarvest(id, actualYield);
        // 处理后端返回的数据结构
        if (response.success) {
          // 重新获取种植记录列表，确保数据最新
          await this.fetchPlantings();
          return Promise.resolve(true);
        }
        return Promise.reject(new Error(response.message || '记录收获失败'));
      } catch (error) {
        console.error('记录收获失败', error);
        throw error;
      }
    },

    // 获取肥料库存
    async fetchFertilizerInventory() {
      try {
        const response = await getInventoryByType('肥料');
        if (response.success && response.data) {
          // 给每个肥料库存项增加itemId字段（确保与原始肥料ID一致）
          const inventory = response.data || [];
          return inventory.map(item => ({
            ...item,
            itemId: item.id // 使用库存ID作为肥料ID
          }));
        } else {
          console.error('获取肥料库存失败', response.message);
          return [];
        }
      } catch (error) {
        console.error('获取肥料库存失败', error);
        return [];
      }
    },

    // 上传产品图片
    async uploadProductImage(file) {
      try {
        console.log('Store方法 - 上传产品图片，文件对象:', file);
        if (!file) {
          throw new Error('文件对象为空');
        }
        
        if (!(file instanceof File)) {
          console.warn('传入的不是标准File对象，类型是:', Object.prototype.toString.call(file));
        }
        
        const response = await uploadProductImage(file);
        return response;
      } catch (error) {
        console.error('上传产品图片失败', error);
        throw error;
      }
    },

    // 上架产品
    async publishProduct(id) {
      try {
        console.log('上架产品', id);
        const response = await publishProduct(id);
        return response;
      } catch (error) {
        console.error('上架产品失败', error);
        throw error;
      }
    },

    // 下架产品
    async unpublishProduct(id) {
      try {
        console.log('下架产品', id);
        const response = await unpublishProduct(id);
        return response;
      } catch (error) {
        console.error('下架产品失败', error);
        throw error;
      }
    },

    // 支付订单
    async payOrder(orderId) {
      try {
        const response = await payOrder(orderId);
        console.log('支付订单成功:', response);
        return Promise.resolve(true);
      } catch (error) {
        console.error('支付订单失败', error);
        return Promise.reject(error);
      }
    }
  }
}); 